"""


"""

import pandas as pd
import json
import os
from tqdm import tqdm

# 移动平均函数
def moving_average(data, window_size):
    return data.rolling(window=window_size, min_periods=1).mean()

# 指数平滑函数
def exponential_smoothing(data, alpha):
    smoothed_data = [data[0]]  # 初始化平滑数据
    for value in data[1:]:
        smoothed_value = alpha * value + (1 - alpha) * smoothed_data[-1]
        smoothed_data.append(smoothed_value)
    return smoothed_data

# 读取 JSON 文件
input_dir = 'fujian/fujian1/json_output'
output_dir = 'fujian/fujian1/preprocessed'
os.makedirs(output_dir, exist_ok=True)

# 获取 JSON 文件列表
json_files = [f for f in os.listdir(input_dir) if f.endswith('.json')]

# tqdm 进度条
with tqdm(total=len(json_files)) as pbar:
    for idx, json_file in enumerate(json_files, start=1):
        # 更新进度条描述，显示当前处理的文件数
        pbar.set_description(f"Processing JSON files {idx} / {len(json_files)}")

        # 读取 JSON 文件
        file_path = os.path.join(input_dir, json_file)
        with open(file_path, 'r') as f:
            records = json.load(f)

        # 提取 qty 数据
        qty_data = [record['qty'] for record in records]

        # 进行移动平均和指数平滑处理
        moving_avg_data = moving_average(pd.Series(qty_data), window_size=9).tolist()
        smoothed_data = exponential_smoothing(qty_data, alpha=0.45)

        # 更新记录中的 qty 数据为平滑后的数据
        for i in range(len(records)):
            records[i]['qty_moving_avg'] = moving_avg_data[i]
            records[i]['qty_smoothed'] = smoothed_data[i]

        # 输出处理后的 JSON 文件
        output_filename = f"processed_{json_file}"
        output_filepath = os.path.join(output_dir, output_filename)
        with open(output_filepath, 'w') as out_file:
            json.dump(records, out_file, indent=4)

        # 更新进度条
        pbar.update(1)

print("All JSON files have been preprocessed.")
